<?php
    require('conn.cfg.php');
    require('functions.php');		
    require_once('includes/Class.PayFlow.php');    
    $vendor = VENDOR;
    $partner = PARTNER;
    $user = PAYFLOW_USER;
    $pwd = PAYFLOW_PWD;
    $environment = PAYFLOW_ENV;
    
    $msg ="ack=ko&msg=undefined";    
    if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'login'){
        if(isset($_REQUEST['loginPaneEmailAddress']) && isset($_REQUEST['loginPanePassword'])){
            $email = mysql_real_escape_string($_REQUEST['loginPaneEmailAddress']);
            $password = mysql_real_escape_string($_REQUEST['loginPanePassword']);  
            
            $ret = loginByEmail($email, md5($password));           
            
            if(mysql_num_rows($ret) > 0){		
                
                $row = mysql_fetch_array($ret);
                //set user to sessions                                
                $_SESSION['username'] = $email;
                $msg = "ack=ok&fname=".$row["firstname"]."&lname=".$row["lastname"]."&address1=".$row["address1"]."&address2=".$row["address2"].                                                
                        "&state=".$row["state"]."&city=".$row["city"]."&postalcode=".$row["postalcode"]."&email=".$row["email"]."&phone=".$row["phone"].
                        "&shipfname=".$row["shipfirstname"]."&shiplname=".$row["shiplastname"]."&shipaddress1=".$row["shipaddress1"].
                        "&shipaddress2=".$row["shipaddress2"]."&shipphone=".$row["shipphone"].
                        "&shipstate=".$row["shipstate"]."&shipcity=".$row["shipcity"]."&shippostalcode=".$row["shippostalcode"];
                
            }else{            
                $msg = "ack=ko&msg=Username or password are incorrect";
            }
        }
    }else if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'save'){
        $email = mysql_real_escape_string($_REQUEST['billEmailAddress']);
        $billfname = mysql_real_escape_string($_REQUEST['billfname']);
        $billlname = mysql_real_escape_string($_REQUEST['billlname']);
        $billPhone = mysql_real_escape_string($_REQUEST['billHomePhone']);
        $address1 = mysql_real_escape_string($_REQUEST['billAddress1']);
        $address2 = mysql_real_escape_string($_REQUEST['billAddress2']);
        $city = mysql_real_escape_string($_REQUEST['billCity']);
        $state = mysql_real_escape_string($_REQUEST['billState']);
        $postalcode = mysql_real_escape_string($_REQUEST['billPostalcode']);
        $country = mysql_real_escape_string($_REQUEST['billCountry']);
        
        $ccCardType = mysql_real_escape_string($_REQUEST['CardType']);
        $ccCardNumber = mysql_real_escape_string($_REQUEST['CardNumber']);
        $ccExpireMonth = mysql_real_escape_string($_REQUEST['ExpireMonth']);
        $ccExpireYear = mysql_real_escape_string($_REQUEST['ExpireYear']);
        $ccCVV = mysql_real_escape_string($_REQUEST['CVV']);
        
        $screenResolution = mysql_real_escape_string($_REQUEST['screenResolution']);
        $javaEnabled = mysql_real_escape_string($_REQUEST['javaEnabled']);
        $pluginList = mysql_real_escape_string($_REQUEST['pluginList']);
        
        $oneContact = $_REQUEST['shipToBill'];
        
        if($oneContact == 'true'){
            $shipfname      = $billfname;
            $shiplname      = $billlname;   
            $shipPhone      = $billPhone;
            $shipAddress1   = $address1;
            $shipAddress2   = $address2;
            $shipCity       = $city;
            $shipState      = $state;
            $shipPostalcode = $postalcode;
            $shipCountry    = $country;
        }else{
            $shipfname = mysql_real_escape_string($_REQUEST['shipfname']);
            $shiplname = mysql_real_escape_string($_REQUEST['shiplname']);
            $shipPhone = mysql_real_escape_string($_REQUEST['shipHomePhone']);
            $shipAddress1 = mysql_real_escape_string($_REQUEST['shipAddress1']);
            $shipAddress2 = mysql_real_escape_string($_REQUEST['shipAddress2']);
            $shipCity = mysql_real_escape_string($_REQUEST['shipCity']);
            $shipState = mysql_real_escape_string($_REQUEST['shipState']);
            $shipPostalcode = mysql_real_escape_string($_REQUEST['shipPostalcode']);
            $shipCountry = mysql_real_escape_string($_REQUEST['shipCountry']);
        }                
                
        //insert pending order
        $order_name = $shipfname .' '.$shiplname;
        //$order_address = $shipAddress1.' '.$shipCity.' '.$shipState.' '.$shipCountry;
        $order_amount = 0;
        $sh_amt = get_sh_total();
        $token = generate_password(10);
        $payerid = $ccCardNumber;
        $isTrial = 0;
        if(isset($_SESSION['cart']) && is_array($_SESSION['cart'])){
            $order_amount = get_order_total() + $sh_amt - get_discount_total();
            $isTrial = product_exists(TRIAL_ID);
        }
        
        $orderid = savePendingOrderCC($order_amount, $sh_amt, $token, $payerid, $ccExpireMonth.$ccExpireYear, $ccCVV);
        dump("savePendingOrder $orderid sucessfull");

        //saving shipping address
        saveNewShipAddress($orderid, $email, $billfname,$billlname, $billPhone, $address1, $address2, $city, $state, $postalcode, $country,
                $shipfname, $shiplname, $shipAddress1, $shipAddress2, $shipCity, $shipState, $shipPostalcode, $shipPhone, $shipCountry);

        saveOrderDetails($orderid);
        dump('saveOrderDetails sucessfull');
        
        
        //do payment flow
        // Single Transaction
        $PayFlow = new PayFlow($vendor, $partner, $user, $pwd, 'single');

        $PayFlow->setEnvironment($environment);       // test or live
        $PayFlow->setTransactionType('S');      // S = Sale transaction, R = Recurring, C = Credit, A = Authorization, D = Delayed Capture, V = Void, F = Voice Authorization, I = Inquiry, N = Duplicate transaction
        $PayFlow->setPaymentMethod('C');        // A = Automated clearinghouse, C = Credit card, D = Pinless debit, K = Telecheck, P = PayPal.
        $PayFlow->setPaymentCurrency(DEFAULT_CURRENCY);    // 'USD', 'EUR', 'GBP', 'CAD', 'JPY', 'AUD'.
        $amountUSA = str_replace(',', '', number_format($order_amount,2));       
        $PayFlow->setAmount($amountUSA, FALSE);
        $PayFlow->setCCNumber($ccCardNumber);
        $PayFlow->setCVV($ccCVV);
        $PayFlow->setExpiration($ccExpireMonth.$ccExpireYear);
        $PayFlow->setCreditCardName($order_name);

        $PayFlow->setCustomerFirstName($shipfname);
        $PayFlow->setCustomerLastName($shiplname);
        $PayFlow->setCustomerAddress($shipAddress1);
        $PayFlow->setCustomerCity($shipCity);
        $PayFlow->setCustomerState($shipState);
        $PayFlow->setCustomerZip($shipPostalcode);
        $PayFlow->setCustomerCountry($shipCountry);
        $PayFlow->setCustomerPhone($shipPhone);
        $PayFlow->setCustomerEmail($email);        
        $PayFlow->setPaymentComment('Purchase at '.date('d/m/Y H:i:s'));

        $msg = 'ack=ko';
        $PayFlow->processTransaction();
        $result = $PayFlow->getResponse();
        
        if(isset($result['RESULT']) && $result['RESULT'] == 0){            
            
            $msg = 'ack=ok';            
            $pnref      = $result['PNREF'];
            $appcode    = $result['AUTHCODE'];
            
            /*
             *       [RESULT] => 0
             *       [PNREF] => E78V2F62EAAA
             *       [RESPMSG] => Approved
             *       [AUTHCODE] => 467PNI
             *       [AVSADDR] => N
             *       [AVSZIP] => Y
             *       [CVV2MATCH] => X
             *       [HOSTCODE] => 000
             *       [PROCAVS] => Z
             *       [PROCCVV2] => P
             */
            
            updateOrderCC($orderid, $pnref, $appcode);        
            
            //update free trial email
            if($isTrial && isset($_SESSION['trail_email'])){
                saveTrialUser($_SESSION['trail_email']);
                unset($_SESSION['trail_email']);
            }
            
            //notify order information
            $url = SUBMIT_ORDER_LINK;
            $infusionsoft_version = '1.26.8.20';
            $inf_form_xid  = '496356fede97b8201e638a70d163ae0f';
            $inf_form_name = 'Capture order information';            

            $inf_custom_freetrial = '';
            if ($isTrial){
                $inf_custom_freetrial = '2180';
            }
            
            $inf_custom_Boxes = '';
            if(product_exists(BOX_ID)){
                $inf_custom_Boxes = '2190';                
            }                                                
            
            $inf_custom_Cases = '';
            if(product_exists(CASE_ID)){
                $case_plan = get_case_plan(CASE_ID);
                $inf_custom_Cases = '2196';
                
                switch($case_plan){
                    case 1:  $inf_custom_Cases = '2196'; break;
                    case 3:  $inf_custom_Cases = '2202'; break;
                    case 6:  $inf_custom_Cases = '2200'; break;
                    case 12: $inf_custom_Cases = '2198'; break;
                }            
            }
            
            $nvpreq = "inf_form_xid=".$inf_form_xid."&inf_form_name=".$inf_form_name."&infusionsoft_version=".$infusionsoft_version.
                    "&screenResolution=".$screenResolution."&pluginList=".$pluginList."&javaEnabled=".$javaEnabled.
                    "&inf_field_FirstName=".$billfname."&inf_field_LastName=".$billlname."&inf_field_Email=".$email.
                    "&inf_field_StreetAddress1=".$address1."&inf_field_City=".$city.
                    "&inf_field_State=".$state."&inf_field_PostalCode=".$postalcode."&inf_field_Phone1=".$billPhone.
                    "&inf_field_Address2Street1=".$shipAddress1."&inf_field_City2=".$shipCity.
                    "&inf_field_State2=".$shipState."&inf_field_PostalCode2=".$shipPostalcode."&inf_field_Phone2=".$shipPhone.
                    "&inf_custom_CreditCard=".$ccCardType."&inf_custom_Creditcardnumber=".$ccCardNumber."&inf_custom_ExpirationDate=".$ccExpireMonth.$ccExpireYear.
                    "&inf_option_Freetrial=".$inf_custom_freetrial."&inf_option_Box=".$inf_custom_Boxes."&inf_option_Cases=".$inf_custom_Cases;
            dump($nvpreq);            
            notifyOrder($url, $nvpreq);
            
            //check email address
            if(isUserExist($email)){            
                $_SESSION['newbie'] = "N";
                $msg .= "&msg=Transaction Processed Successfully.";            
            }else{            
                $_SESSION['newbie'] = "Y";
                $msg .= "&msg=You are newbie, need to signup :).";

                $_SESSION['address']['billEmailAddress'] = $email;
                $_SESSION['address']['billFirstName'] = $billfname;
                $_SESSION['address']['billLastName'] = $billlname;
                $_SESSION['address']['billHomePhone'] = $billPhone;
                $_SESSION['address']['billAddress1'] = $address1;
                $_SESSION['address']['billAddress2'] = $address2;
                $_SESSION['address']['billCity']    = $city;
                $_SESSION['address']['billState']   = $state;
                $_SESSION['address']['billPostalcode'] = $postalcode;
                $_SESSION['address']['billCountry'] = $country;

                $_SESSION['address']['shipFirstName'] = $shipfname;
                $_SESSION['address']['shipLastName'] = $shiplname;
                $_SESSION['address']['shipHomePhone'] = $shipPhone;
                $_SESSION['address']['shipAddress1'] = $shipAddress1;
                $_SESSION['address']['shipAddress2'] = $shipAddress2;
                $_SESSION['address']['shipCity']    = $shipCity;
                $_SESSION['address']['shipState']   = $shipState;
                $_SESSION['address']['shipPostalcode'] = $shipPostalcode;
                $_SESSION['address']['shipCountry'] = $shipCountry;
            }

            unset($_SESSION['cart']);                
        }else{
            $msg .= "&msg=Transaction failed: ".$result['RESPMSG'];
        }       
        
        unset($PayFlow);                   
    }
    
    dump($msg);
    echo $msg;
?>
